Ext.namespace("Ext.qd");
Ext.namespace("Ext.qd.nzb");
Ext.qd.nzb.loadFilesGrid = function(pathname ){
	Ext.getCmp('gridfiles').pathname = pathname ; 
	Ext.getCmp('gridfiles').store.removeAll()
	Ext.getCmp('gridfiles').store.load({
		params :{
		exw_action : 'QDNzbProxy.getFiles',      
		fullpath : pathname,
		only2Rename:Ext.getCmp('only2Rename').pressed      
	}     
	});
}

Ext.qd.nzb.clickOnTreeFolderNode = function(node){
	if (Ext.getCmp('folderTree').getSelectionModel().isSelected(node)){
		if(node.attributes.fullname!=-1){
			Ext.qd.nzb.loadFilesGrid(node.attributes.fullname);
			if (!node.attributes.tvdb){
				Ext.qd.nzb.chooseSerie(node);
			}
		}
	}
}


Ext.qd.nzb.SeriesPanel = Ext.extend(Ext.Panel, {
	initComponent : function() { 
	this.expander = new Ext.grid.RowExpander({
		tpl : new Ext.Template('{Overview}')
	});
	var sm = new Ext.grid.CheckboxSelectionModel();
	Ext.apply(this,{
		layout    : 'border',
		items     : [{
			xtype     : 'tabpanel',
			region    :'west',
			activeTab : 0,
			width   : 300,      
			items     : [{
				xtype     : 'columntree',
				title     : 'folders',
				id        : 'folderTree',
				loadMask  : true,      
				split     : true,
				rootVisible:false,
				lines     : true,
				selModel  : new Ext.tree.MultiSelectionModel(),
				fitToFrame: true,    
				autoScroll:true, 
				containerScroll: true,
				root      : new Ext.tree.AsyncTreeNode({
					text         : 'drives',
					fullfilename : -1,
					draggable    : false
				}),
				listeners : {
				click : Ext.qd.nzb.clickOnTreeFolderNode,
				contextMenu : function(node){
				console.log(node);
				var prmCtx = {
						id:'folderCtx',
						items: [{
							id:'getMulti',
							handler:function(a,b){
							Ext.getCmp('gridfiles').store.load({
								params :{
								fullpath : node.attributes.fullname,
								exw_action : 'QDNzbProxy.getFilesMulti',      
								only2Rename:Ext.getCmp('only2Rename').pressed
							}     
							});
						},            
						text:'getMulti'
						}]
				};
				if (!node.attributes.rootDrive){
					prmCtx.items.push({
						id:'setSerie',
						handler:function(a,b){
						Ext.qd.nzb.chooseSerie(node);          
					},            
					text:'set Serie'
					});    
				}    

				var ctxMenu = new Ext.menu.Menu(prmCtx);
				ctxMenu.show(node.ui.getAnchor());

			}
			},
			tbar            : [{
				text            : 'refresh',
				handler         : function(){
				var ftree = Ext.getCmp('folderTree');
				ftree.loader.baseParams.refresh = 1; 
				ftree.loader.load(ftree.getRootNode());
			}
			}],

			columns:[{
				header:'folder',
				width:200,
				dataIndex:'text'
			},{
				header    :'TVDB',
				width     :32,
				dataIndex :'tvdb',
				renderer  : function (a,b,c){
				return (b.attributes.tvdb?'<img src="skins/resources/tvdb.jpg">':'');
			}
			}/*,{
              header:'action',
              width:100,
              cbIconCls : 'tree-icon-edit',
              callback : function(tree,node,action){
                Ext.qd.nzb.chooseSerie(node);
                //console.log(tree,node,action);
              }
          }*/],
          loader: new Ext.tree.TreeLoader({
        	  dataUrl:'proxy.php?exw_action=QDNzbProxy.getSeriesTree',
        	  //dataUrl:'cache/column-data.json',
        	  uiProviders:{
        	  'col': Ext.tree.ColumnNodeUI
          }
          }),            
			}]  
		},{
			layout : 'border',
			region : 'center',
			items : [{
				height : 100,
				region : 'north',
				frame  : true,
				border : false,
				layout : 'table',
				defaults :{
				height : 80,
				border : false
			},
			items : [{
				id     : 'bannerImg',
				width  : 320          
			},{
				id     : 'bannerText',
				autoScroll : true
			}]
			},{
				xtype : 'tabpanel',
				region : 'center',
				activeTab : 0,
				deferredRender :false,
				items : [{
					xtype : 'editorgrid',
					id     : 'gridfiles',
					title  : 'Files',
					loadMask: true,
					selModel : sm,
					tbar : [{
						text    : 'Select all',
						handler : function(){
						Ext.getCmp('gridfiles').getSelectionModel().selectAll();
					} 
					},{
						text : 'Rename',
						handler : function(){
						//var arrModified = Ext.getCmp('gridfiles').getStore().data.items;
						var arrModified = Ext.getCmp('gridfiles').getSelectionModel().selections.items;
						var arrResult = {};
						Ext.each(arrModified,function(v,k){
							console.log(v);
							if (!arrResult[Ext.util.base64.encode(v.data.pathName)]){
								arrResult[Ext.util.base64.encode(v.data.pathName)]={};
								arrResult[Ext.util.base64.encode(v.data.pathName)].modified=[];
							}
							arrResult[Ext.util.base64.encode(v.data.pathName)].modified.push({
								//'old' : v.data.filename, 
								//'new'    : v.data.episodeName,
								'new64'  : Ext.util.base64.encode((v.data.episodeName+' ').trim()),                
								'saison' : v.data.saison,
								'ext'    : v.data.ext,
								'episode': v.data.episode,
								'md5'    : v.data.md5,                
								'serie'  : Ext.util.base64.encode(v.data.serieName)
							});
						});
						console.log(arrResult);
						Ext.Ajax.request({
							url      : 'proxy.php',
							params : {
							exw_action : 'QDNzbProxy.renameFiles',
							modified   : Ext.util.base64.encode(Ext.util.JSON.encode(arrResult))
						},
						success : function(r){
							Ext.qd.nzb.loadFilesGrid(Ext.getCmp('gridfiles').pathname);
						}
						});
					}  
					},{
						text    : 'Un-Select all',
						handler : function(){
						Ext.getCmp('gridfiles').getSelectionModel().clearSelections();
					} 
					},{
						text    : 'Only to rename',
						id      : 'only2Rename',
						enableToggle   : true,
						pressed : true
					},{
						text    : 'Invert Selection',
						handler : function(){
						//Ext.getCmp('gridfiles').getSelectionModel().clearSelections();
						alert('to do');
					} 
					}],
					clicksToEdit : 1,
					store: new Ext.data.JsonStore({
						url      : 'proxy.php',
						baseParams : {
						//exw_action : 'QDNzbProxy.getFiles'            
					},
					root: 'results',
					pruneModifiedRecords  : true,
					fields: [
					         {name: 'filename'   },
					         {name: 'ext'        },
					         {name: 'saison'     },
					         {name: 'episode'    },
					         {name: 'episodeName'},
					         {name: 'filesize'   },
					         {name: 'Overview'   },             
					         {name: 'md5'        },
					         {name: 'serieName'  },
					         {name: 'pathName'   }             
					         ],
					         listeners : {
						datachanged  :function(){
						console.log(this);
					},
					load : function(r,b){
						Ext.getCmp('bannerText').body.update(r.reader.jsonData.bannerText);
						Ext.getCmp('bannerImg' ).body.update('<img border="0" src="'+(r.reader.jsonData.bannerImg?'http://thetvdb.com/banners/_cache/'+r.reader.jsonData.bannerImg:'skins/resources/images/default/s.gif')+'">');
						if(r.reader.jsonData.serieHTML && Ext.getCmp('serieHTML' ).body) Ext.getCmp('serieHTML' ).body.update(Ext.util.base64.decode(r.reader.jsonData.serieHTML));
						Ext.getCmp('gridfiles').SerieName = r.reader.jsonData.serieName ; 

					}
					}
					}),
					plugins : [this.expander],
					columns: [
					          sm,
					          this.expander,      
					          {header: "Episode" , width:   280, dataIndex: 'episodeName' , sortable: true,editor:new Ext.form.TextField({allowBlank:false})},
					          {header: "S"       , width:    30, dataIndex: 'saison'      , sortable: true},          
					          {header: "E"       , width:    30, dataIndex: 'episode'     , sortable: true},          
					          {header: "Name"    , width:   300, dataIndex: 'filename'    , sortable: true},          
					          {header: "Type"    , width:    40, dataIndex: 'ext'         , sortable: true},          
					          {header: "Size"    , width:    80, dataIndex: 'filesize'    , sortable: true}

					          ]
				},{
					title : 'Episodes',
					id : 'serieHTML',
					html : '',
					autoScroll : true
				}]
			}]
		}]
	});
	//Ext.getCmp('folderTree').getRootNode().load();
	/*
  Ext.Ajax.request({
    url      : 'proxy.php',
    params : {
      exw_action : 'QDNzbProxy.getTree'
    },
    success : function(r){
      var json = Ext.util.JSON.decode(r.responseText);
      var root = Ext.getCmp('folderTree').getRootNode();
      var tree = Ext.getCmp('folderTree');
      for(var i = 0, len = json.length; i < len; i++) {
        tree.getLoader().uiProviders = {
              'col': Ext.ux.ColumnNodeUI
          };

        root.appendChild(tree.getLoader().createNode(json[i]));
      }
    }
  });*/

	Ext.qd.nzb.SeriesPanel.superclass.initComponent.apply(this, arguments);
}

});
Ext.reg('nzb.SeriesPanel',Ext.qd.nzb.SeriesPanel)

Ext.qd.nzb.chooseSerie = function (node){
	var expander = new Ext.grid.RowExpander({
		tpl : new Ext.Template('{Overview}')
	});
	var sm = new Ext.grid.CheckboxSelectionModel();
	var win = new Ext.Window({
		width:400,
		height:300,
		modal : true,
		layout : 'border',
		items : [{
			xtype : 'panel',
			region : 'north',
			layout : 'table',
			frame : true,     
			height : 35,
			items : [{
				html  :'Serie :&nbsp;'        
			},{
				xtype : 'textfield',        
				id : 'textchooseserie',
				width : 250,               
				enableKeyEvents : true,
				height    : 20,
				listeners: { 
				keypress: function(ob,e){
				if (e.getCharCode()==13){
					Ext.getCmp('butchooseserie').events.click.listeners[0].fn();
				}
			}
			}      
			},{
				xtype : 'button',
				text  : 'search',
				id    : 'butchooseserie',
				listeners :{
				click :  function(){
				Ext.getCmp('gridchooseserie').store.load({
					params : {
					s : Ext.getCmp('textchooseserie').getValue(),
					p : node.attributes.fullname
				} 
				});
			}
			}
			}]
		},{
			xtype  : 'grid',
			region : 'center',
			id     : 'gridchooseserie',
			height : 200,
			loadMask: true,
			store  : new Ext.data.JsonStore({
				url      : 'proxy.php',
				pruneModifiedRecords:true,        
				baseParams : {
				exw_action : 'QDNzbProxy.chooseSerie'            
			},
			root   : 'results',
			fields : [
			          'name',
			          'lang',
			          'Overview',
			          'seriesid',
			          'year'             
			          ],
			          listeners :{ 
				load : function (r){
				if (this.reader.jsonData.seriesid){
					var t = Ext.getCmp('gridchooseserie').store.query('seriesid',this.reader.jsonData.seriesid);
					Ext.getCmp('gridchooseserie').getSelectionModel().selectRecords(t)
					//console.log(this.reader.jsonData.seriesid);
					//console.log(node);              
				}
			}
			}
			}),
			selectionModel : sm,
			plugins : expander,
			columns: [
			          sm,
			          expander,
			          {header: "name" , width:  200, dataIndex: 'name'   , sortable: true},          
			          {header: "lang" , width:  80, dataIndex: 'lang'   , sortable: true},          
			          {header: "year" , width:  80, dataIndex: 'year'   , sortable: true}          
			          ]

		}],
		buttons :[{ 
			text : 'ok',
			handler : function(){
			var recordSelected = Ext.getCmp('gridchooseserie').getSelectionModel().getSelected();
			if (recordSelected){
				var w = Ext.MessageBox.wait('mise à jour');
				Ext.Ajax.request({
					url    : 'proxy.php',
					params : {
					exw_action : 'QDNzbProxy.setSerieFromPath',
					p          : node.attributes.fullname,
					i          : recordSelected.data.seriesid
				},
				success : function(r){
					var r = Ext.util.JSON.decode(r.responseText)
					Ext.getCmp('textchooseserie').setValue(r.results.name);
					Ext.getCmp('butchooseserie').events.click.listeners[0].fn();
					//node.setText(r.results.title);
					w.hide();
					node.attributes.tvdb= true;
					node.expand();
					//Ext.qd.nzb.clickOnTreeFolderNode(node);
					Ext.each(node.childNodes,function(v){
						v.attributes.tvdb=true;
					});
					refreshNodeColumns(node);
					////////////////      
				}         
				});
				win.hide();
			}else{
				Ext.MessageBox.alert('Error','rien de selectionné');
			}
		}    
		},{ 
			text : 'cancel',
			handler : function(){
			win.close();
		}   
		}],
		listeners : {
		show  : function(){
		Ext.Ajax.request({
			url    : 'proxy.php',
			params : {
			exw_action : 'QDNzbProxy.getSerieFromPath',
			p          : node.attributes.fullname
		},
		success : function(r){
			var r = Ext.util.JSON.decode(r.responseText)
			Ext.getCmp('textchooseserie').setValue(r.results.name);
			Ext.getCmp('butchooseserie').events.click.listeners[0].fn();      
		}         
		})
	}
	}
	})
	win.show();
}
